package com.example.demo.utils;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;


public class CookieUtil {
	
	private CookieUtil() {};
	 /**
	  	* 设置cookie
     * @param response
     * @param name
     * @param value
     * @param maxAge
     */
    public static void set(HttpServletResponse response,
                           String name,
                           String value,
                           int maxAge){
        Cookie cookie = new Cookie(name, value); //设置cookie的key和value值
        cookie.setSecure(false);
        cookie.setPath("/");        //路径
        cookie.setMaxAge(maxAge);   //过期时间
        response.addCookie(cookie); //添加cookie
    }
    /**
     	* 清空
     * @param request
     * @param response
     * @param name
     */
    public static void clear(HttpServletRequest request,
    		HttpServletResponse response,
            String name){
			String value=get(request, name);
			if (!StringUtils.isEmpty(value)) {
				set(response, name, value, 0);
			}
	}

    /**
     	* 获取cookie
     * @param request
     * @param name
     * @return
     */
    public static String get(HttpServletRequest request,
                           String name){
        Map<String, String> cookieMap = readCookieMap(request);
        
        return cookieMap.get(name);
       
    }

    /**
     	* 将cookie封装成map
     * @param request
     * @return
     */
    private static Map<String, String> readCookieMap(HttpServletRequest request){
        Map<String, String> cookieMap = new HashMap<>();
        Cookie[] cookies = request.getCookies();        //获取所有的cookie值
        if(cookies != null){
            for (Cookie cookie : cookies){
                cookieMap.put(cookie.getName(),cookie.getValue());
            }
        }
        return cookieMap;
    }
}
